package Threads;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import Debug.Debug;
import Interfaces.C_interface;
import Interfaces.S_interface;
import Structs.Log;
import Structs.Member;
import Structs.Msg_broad;
import Structs.Task;
import UI.Server_Drop;

public class S_RMI extends UnicastRemoteObject implements S_interface{

	private int RMI_port;
	
	private Hashtable<String,Member> Clients;
	private Hashtable<String, Object> OnlineClients;
	private Hashtable<Integer,Task> Tasks;
	
	private BlockingQueue<Task> rmi_requests;
	private BlockingQueue<Msg_broad> Broadcast;
	private BlockingDeque<Log> log;
	
	private S_dispatcher dispatcher;

	public S_RMI(int port, 
				Hashtable<String,Member> Clients, 
				Hashtable<String,Object> OnlineClients,
				Hashtable Tasks,
				BlockingQueue<Task> rmi_requests,
				BlockingQueue<Msg_broad> Broadcast,
				BlockingDeque<Log> log) throws RemoteException {
		
		super();
		
		this.RMI_port=port;
		this.Clients = Clients;
		this.OnlineClients = OnlineClients;
		this.Tasks = Tasks;
		this.Broadcast = Broadcast;
		this.log = log;
		this.rmi_requests =  rmi_requests;
		
	}
	
	private static final long serialVersionUID = 1L;


	public boolean Login(String Username, String Password, C_interface client) throws RemoteException{
		if(Clients.containsKey(Username)){
			
			if(Clients.get(Username).getPass().equals(Password)){
				OnlineClients.put(Username, client);
				return true;
			}
		}
		
		return false;
	}
	
	public boolean Logout(String Username) throws RemoteException{
		if(OnlineClients.containsKey(Username)){
			OnlineClients.remove(Username);
			return true;
		}
		return false;
	}

	public boolean Register(String Username,String Password) throws RemoteException{
		if(!Clients.containsKey(Username)){
			Clients.put(Username,new Member(Username, Password));
			return true;
		}
		return false;
	}
	
	public boolean addTask(int id,String Title,Member User, GregorianCalendar Date)throws RemoteException{
		rmi_requests.add(new Task(id,Title,User,Date));
		return true;
	}
	
	public boolean addTask(String Title,Member User, GregorianCalendar Date)throws RemoteException{
		rmi_requests.add(new Task(0,Title,User,Date));
		return true;
	}
	
	public String ListTasks()throws RemoteException{
		String message = "";
		Enumeration<Integer> id_e = Tasks.keys();
		Integer id;
		Task temp;
		
		while(id_e.hasMoreElements()){
			
			id = id_e.nextElement();
			message = message+Tasks.get(id).toMessageString(id)+"\n";
	
		};
	
	
		return message;
	}
}
